import React, { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
interface IProps {
  visible: boolean;
  children?: React.ReactNode | JSX.Element;
  onCancel?: () => void;
  width?: string | number;
  height?: string | number;
}

export default ({
  visible,
  children,
  onCancel,
  width = 300,
  height,
}: IProps) => {
  const [isOpen, setIsOpen] = useState(false);

  useEffect(() => {
    setIsOpen(visible);
  }, [visible]);

  const modalContainerStyle: React.CSSProperties = {
    width,
    height,
    margin: 'auto',
    padding: '20px 30px',
    borderRadius: '2px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.33)',
    transition: 'all 0.3s ease',
    background: '#fff',
    display: 'flex',
    flexDirection: 'column',
  };

  return isOpen
    ? createPortal(
      <div
        style={{ background: '#00000080' }}
        className="fixed items-center transition:opacity 0.3s ease justify-center w-full h-full top-0 left-0 z-200 flex"
      >
        <div style={modalContainerStyle}>
          <div>{children}</div>

          <div className="ml-2 text-right">
            <button
              type="button"
              onClick={() => {
                setIsOpen(false);
                onCancel?.();
              }}
              className="px-4 py-2 text-sm font-semibold text-white rounded-full shadow-sm bg-cyan-500"
            >
              close
            </button>
          </div>
        </div>
      </div>,
      document.body,
    )
    : null;
};
